window.onload = function () {
    let cartItem = document.getElementsByClassName('cartItem')[0];
    let str = ''
    Ajax.get('http://10.101.96.3:8000/getCart', (data) => {
        //按得到的信息，显示商品详情
        let cartData = JSON.parse(data)
        // console.log(cartData);
        cartData.forEach((item) => {
            str += `<ul id="${item.id}" class="ul">
                <li class="check">
                    <input type="checkbox" name="" class="checkOne Check" id="ch-inp">
                </li>
                <li class="item">
                    <div class="inner">
                        <div class="item-img "><img src="${item.img}" alt=""></div>
                        <div class="item-info ">${item.title}</div>
                    </div>
                </li>
                <li class="info"></li>
                <li class="price"><span>￥</span><i class="Price">${item.price}</i></li>
                <li class="amount">
                    <div class="amt">
                        <div class="minus">-</div>
                        <input type="text" class="int" value="${item.number}">
                        <div class="plus">+</div>
                    </div>
                </li>
                <li class="sum">￥${item.price}</li>
                <li class="operate">
                    <p>移入收藏夹</p>
                    <p class="delBtn">删除</p>
                </li>
            </ul>`
        });
        cartItem.innerHTML = str;

        //********************************************** 
        let shopCart = document.getElementsByClassName('shopCart')[0];
        let ulTop = document.getElementsByClassName('ulTopSpan')[0];
        let btnArea = document.getElementsByClassName('btn-area')[0];
        let em = document.getElementsByTagName('em')[0];
        let total = document.getElementsByClassName('total-symbol')[0];
        let ul = document.getElementsByClassName('ul');
        let plus = document.getElementsByClassName('plus');
        let minus = document.getElementsByClassName('minus');
        let sum = document.getElementsByClassName('sum');
        let Price = document.getElementsByClassName('Price');
        let int = document.getElementsByClassName('int');
        xiaoji()

        function xiaoji() {
            for (let g = 0; g < ul.length; g++) {
                sum[g].innerText = '￥' + parseFloat(int[g].value * Price[g].innerText).toFixed(2)
            }
        }


        //加一**********************************************

        function addBtn() {
            for (let i = 0; i < plus.length; i++) {
                plus[i].onclick = function () {
                    int[i].value++;
                    sum[i].innerText = '￥' + parseFloat(int[i].value * Price[i].innerText).toFixed(2)
                    getTotal(); //调用函数,重新计算
                };
            }

        };

        //减一**************************************************
        function reduceBtn() {
            for (let i = 0; i < minus.length; i++) {
                minus[i].onclick = function () {
                    if (int[i].value <= 1) {
                        int[i].value == 1
                    } else {
                        int[i].value--
                        sum[i].innerText = '￥' + parseFloat(int[i].value * Price[i].innerText).toFixed(2)
                    }
                    getTotal(); //调用函数,重新计算

                }
            }

        };

        //右边删除***********
        function deleteBtn() {
            var delBtn = document.getElementsByClassName('delBtn');
            for (let i = 0; i < delBtn.length; i++) {
                delBtn[i].index = i
                delBtn[i].onclick = function () {
                    cartItem.removeChild(ul[this.index]);
                    //调用删除后的cartData
                    cartData.splice(this.index, 1)
                    // console.log(cartData)
                    //下面向服务器发请求更新购物车
                    Ajax.post('http://10.101.96.3:8000/updateCart', JSON.stringify(cartData), (data) => {
                        console.log(JSON.parse(data))
                    })
                    getTotal(); //调用函数,重新计算
                    console.log(this.index)
                    //回调，因为删除了，长度改变，要重新循环数组
                    return deleteBtn();
                }
            }

        };
        //下面删除***********
        function Delete() {
            let checkOne = document.getElementsByClassName("checkOne");
            let DeleteSelected = document.getElementsByClassName('DeleteSelected')[0];
            DeleteSelected.onclick = function () {
                for (let k = 0; k < checkOne.length; k++) {
                    if (checkOne[k].checked) {
                        cartItem.removeChild(ul[k]);
                        //删除，长度减少
                        k--;
                        cartData.splice(k, 1)
                        // console.log(cartData)
                        //下面向服务器发请求更新购物车
                        Ajax.post('http://10.101.96.3:8000/updateCart', JSON.stringify(cartData), (data) => {
                            // console.log(JSON.parse(data))
                        })
                    }
                }
                getTotal(); //调用函数,重新计算
            }
        };

        function getTotal() {
            let price = 0;
            let count = 0;
            let sumPrice = 0;
            let checkOne = document.getElementsByClassName("checkOne");
            for (let i = 0; i < checkOne.length; i++) {
                if (checkOne[i].checked) {
                    price += parseFloat(Price[i].innerText);
                    count += parseInt(int[i].value);
                    sumPrice += parseFloat(Price[i].innerText * int[i].value);
                    // console.log(count)
                }
            }
            em.innerText = count;
            total.innerText = '￥' + sumPrice;
            ulTop.innerText = ul.length;
            // 判断价格是否为0，不为零，则背景色为红色；则反之
            if (price != 0) {
                btnArea.style.backgroundColor = '#ff0036'
            } else {
                btnArea.style.backgroundColor = '#b8b8b8'
            }
        };
        //全选
        let Check = getClass('Check');
        for (let i = 0; i < Check.length; i++) {
            Check[i].onclick = function () {
                if (this.className == 'checkAll Check') {
                    for (var j = 0; j < Check.length; j++) {
                        Check[j].checked = this.checked;
                    }
                };
                changeColor();
                getTotal(); //调用合计、件数函数
            };
            Delete()
            deleteBtn(); //调用删除函数
            addBtn(); //调用add函数
            reduceBtn(); //调用减一函数
        };

        //选中背景颜色改变***************************
        function changeColor() {
            let checkOne = document.getElementsByClassName("checkOne");
            for (let k = 0; k < checkOne.length; k++) {
                checkOne[k].index = k;
                if (checkOne[k].checked) {
                    ul[checkOne[k].index].style.backgroundColor = '#fff8e1';
                } else {
                    ul[checkOne[k].index].style.backgroundColor = '#f8f8f8'
                }
            }
        }

        // 封装//得到 check的class
        function getClass(cName) {
            var doms = document.getElementsByTagName('*')
            var domArr = [];
            for (var i = 0; i < doms.length; i++) {
                if (doms[i].className == cName || doms[i].className.indexOf(cName + '') != -1 || doms[i].className.indexOf('' + cName) != -1) {
                    domArr.push(doms[i])
                };
            };
            return domArr;
        };
        // console.log(cartData)
        //判断购物车是否为空，若是，用一张图片代替内容
        isEmpty(); //调用函数,判断购物车是否为空 
        function isEmpty() {
            if (cartData.length == 0) {
                shopCart.style.display = 'none'
                let image = document.createElement('img')
                let h2 = document.createElement('h2')
                let text = document.createTextNode("您的购物车为空，请赶紧行动吧！！！")
                h2.appendChild(text)
                let src = document.createAttribute('src')
                let srcId = document.createAttribute('id')
                srcId.value = "img"
                src.value = "../imgs/shopCart.png"
                image.setAttributeNode(src)
                image.setAttributeNode(srcId)
                document.body.appendChild(image)
                document.body.appendChild(h2)
            }
        }


        //在页面显示登录用户名
        let span = document.getElementById("span")
        let span1 = document.getElementById("span1")
        let login = document.getElementById('login')
        let dataMsg = JSON.parse(localStorage.getItem("dataMsg"))
        let sessionid = getCookie("sessionid")
        if (sessionid != null) {
            span.innerHTML = "你好，" + dataMsg.msg.userInfo.name
            span1.innerHTML = "登出"
            login.innerHTML = ''
        } else {
            span1.innerHTML = ""
        }


        //登出
        let logout = document.getElementById('logout')
        let username = getCookie("username")
        logout.onclick = function () {
            if (username != null) {
                Ajax.post('http://10.101.96.3:8000/logout', JSON.stringify(username), (data) => {
                    console.log(data)
                    // window.location.reload()
                })
            }
        }
    }) //Ajax函数
    function getCookie(name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    }
}